<?php

namespace App\Http\Controllers\Front;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\Redis;
use App\Service\Sms;
use App\Models\Sms as SmsModel;
use Carbon\Carbon;
use Validator;

class PublicController extends ApiController
{
    /**
     * 手机验证
     */
    public function phoneVerification(Request $request)
    {
        if ($request->ajax()) {
            $messages = [
                'phone.required' => '请输入手机号码',
                'code.required' => '请输入验证码',
            ];
    
            $validator = Validator::make($request->all(), [
                'code' => 'required',
                'phone' => 'required'
            ], $messages);

            if ($validator->fails()) {
                return $this->failed($validator->errors()->first());
            }

            $phone = $request->input('phone');
            $code = $request->input('code');
            $recode = Redis::get('phone'.$phone);
            if ($code === $recode) {
                $request->user()->telphone = $phone;
                $request->user()->save();

                Redis::del('phone'.$phone);

                $httpReferer = session('http_referer');
                if (!$httpReferer) {
                    $httpReferer = route('home');
                }
                
                return $this->success($httpReferer);
            } else {
                return $this->failed('验证码校验失败');
            }
        }

        return view('front.public.phoneVerification');
    }

    /**
     * 发送短信
     */
    public function sendSms(Request $request)
    {
        $phone = $request->input('phone');
        
        Redis::setex('phone' . $phone, 300, 131525);
        $recode = Redis::get('phone' . $phone);

        // 判断该手机在10分钟内是否已经发过短信
        // SmsModel::where('to', $phone)->first();
        $exists = Redis::exists('phone' . $phone);
        if(!empty($exists)){
            return $this->failed('已发送,请五分钟之后再试');
        }

        //随机验证码
        $code = rand(100000,999999);

        // 发送验证码
        $response = Sms::sendSms($phone, $code);

        //判断是否发送成功
        if($response->Code === 'OK'){
            //把手机号码存入redis缓存 设置600秒的有效时间
            Redis::setex('phone'.$phone, 300, $code);
            //发送成功返回成功
            return $this->message('发送成功');
        }else{
            //发送失败返回失败
            return $this->failed('发送失败，请重试');
        }
    }

    /**
     * 文件上传
     */
    public function upload(Request $request)
    {
        $user = $request->user();
        $filename = 'file';
        $filepath = storage_path('app/public/uploads/images');
        $errormsg = '';

        //1.首先检查文件是否存在
        if (!$request->hasFile($filename)){ 
            return $this->failed('图片存储失败');
        }
        // 2.获取文件
        $file = $request->file($filename);
        if($file) {
            //4图片后缀是否正确
            $extension = $file->guessExtension();
            if(!in_array(strtolower($extension),['jpeg','jpg','gif','gpeg','png'])){ 
                return $errormsg = '图片类型不正确';
            }
            //4.将文件取一个新的名字
            $newName = time() . uniqid() . '_' . $user->id . '.' . $extension;
            //5.移动文件,并修改名字

            $maxSize = [
                'width' => 1080,
                'height' => 1080,
            ];

            $size = getimagesize($file);
            $w = $size[0];
            $h = $size[1];

            if($w > $maxSize['width'] || $h > $maxSize['height']) {
                $multiple = max($w / $maxSize['width'], $h / $maxSize['height']);
                $resizeW = $w / $multiple;
                $resizeH = $h / $multiple;
            } else { 
                $resizeW = $w;
                $resizeH = $h;
            }

            $img = \Image::make($file)->resize($resizeW, $resizeH, function ($constraint) {
                $constraint->aspectRatio();
            })->save($filepath.'/'.$newName);

            if($img) {
                return $this->success(['name' => $newName, 'path' => config('app.url').'/storage/uploads/images/'.$newName]);
            }else {
                return $this->faild('图片存储失败');
            }

        }else {
            return $this->faild('没有文件上传');
        }
    }

}
